<template>
  <view class="article">
    <uni-nav-bar class="nav-bar" :class="showNavBar ? 'show' : ''" :statusBar="true" :border="false" rightWidth="180rpx"
                 backgroundColor="transparent">
      <template v-slot:left>
        <view class="back" @click="back">
          <uni-icons class="icon" :color="showNavBar ? '#333333' : '#ffffff'" type="left" size="48rpx"></uni-icons>
        </view>
      </template>
      <template v-slot:default>
        <view class="title">
          <text class="text">{{ articles.title }}</text>
        </view>
      </template>
    </uni-nav-bar>
    <view class="cover"><!-- :class="{ placeholder: !coverImage.show, 'not-cover': !coverImage.exists } -->
      <image  class="img show"  :src="bac_top_url"
             mode="aspectFill" @load="setCoverImageSize" style="width: 100%;"></image>
             <!-- :style="{width: `${coverImage.width}px`, height: `${coverImage.height}px`}" -->

      <view class="mask"></view>
    </view>
    <template v-if="!loading">
      <view class="meta">
        <view class="title">
          <text class="text">{{ article.title }}</text>
        </view>
        <view class="excerpt">
          <text class="text">{{ article.description }}</text>
        </view>
        <view class="author">
		  <img src="../../../static/images/user/ico.png" @click="goOtherInfoPage">
          <template v-if="article.authorName">
            <text class="at">{{ article.authorName || '' }}</text>
            <text class="split">·</text>
          </template>
          <text class="date">{{ publishTime(article.createTime) }}</text>
		  <view class="favBtn_author">
			  <uni-fav :checked="followChecked" class="favBtn" star="false" circle="true"
			  bgColor="#eeeeee" bgColorChecked="#007aff" @click="onClickFollowUser()"
			  :contentText="contentText"/>
		  </view>
        </view>
      </view>
      <view class="content">
        <rich-text :nodes="article.content" space ></rich-text>
      </view>
	  <view class="formData">
	  	<uni-fav :checked="collectChecked" class="favBtn" bgColor="#eeeeee" bgColorChecked="#007aff" 
	  	@click="time<=0?onCollectClick():showTimecCountdown()"/>
	  	<view :style="{color: !likeChecked?'#5e6d82':'#007aff'}"><uni-icons :color="!likeChecked?'#5e6d82':'#007aff'" type="hand-up" size="40rpx" @click="addLikeCount()"></uni-icons>点赞</view>
	  	<view><uni-icons type="chat" size="40rpx" @click="goPageChat()"></uni-icons>私信</view>
		<view><uni-icons type="redo" size="40rpx" @click=""></uni-icons>转发</view>
	  </view>
    </template>
    <view class="detail-loading" v-else>
      <uni-icons type="spinner-cycle" size="35px"/>
    </view>
  </view>
</template>

<script>
import API from '@/json/json.js'
import translatePublishTime from "@/pages/photo/common/publish-time";
import request from '../../../utils/request.js';
import {getUserInfo} from '../../../utils/auth.js'
export default {
  components: {},
  data() {
    return {
		id: "", // 文章ID,如果文章类型为0，则为绑定的普通文章id
		articleType: 1,//指定请求时文章类型，1为普通文章，0为ai文章
		isRandom: false,//是否随机获取
		bac_top_url: '',//封面图片链接
		time: 15000,//倒计时时间，单位ms 
	    collectChecked: false,//是否收藏
	    likeChecked: false,//是否点赞
		followChecked: false,//是否点击关注作者按钮
	    loading: true,//是否加载中
        showNavBar: false, // 是否显示导航栏
		contentText: {contentDefault: '关注',contentFav: '已关注'},//按钮内容
        coverImage: { // 封面图片相关信息
        url: '', // 图片链接
        exists: true, // 是否存在
        show: false, // 是否显示
        width: 1, // 宽度
        height: 1// 高度
        },
        article: {
		 authorId: "",//作者id
	   	 title: "", // 文章标题
		 describe: "",//文章介绍
	   	 content: "",//文章内容
		 createTime: "",//创建时间
	    },
      // 广告相关配置
      adpId: "", // TODO: 请填写广告位ID
      watchAdUniqueType: "device" // TODO: 观看广告的唯一标识类型，可选值为 user 或者 device，user 表示用户唯一，device 表示设备唯一
    }
  },
  computed: {},
  onReady() {
    // 开始加载数据，修改 where 条件后才开始去加载 clinetDB 的数据 ，需要等组件渲染完毕后才开始执行 loadData，所以不能再 onLoad 中执行
    if (this.id) { // ID 不为空，则发起查询
      this.loadData(this.id)
	  
    } else {
      uni.showToast({
        icon: 'none',
        title: 'id 不能为空'
      })
    }
  },
  onLoad(event) {
    //获取文章id，通常 id 来自上一个页面
    if (event.id) {
      this.id = event.id
    }
	//获取文章isRandom，通常 isRandom 来自上一个页面
	if (event.isRandom) {
		this.isRandom = event.isRandom
	}
	//获取文章类型，1为普通文章，0为ai文章通常 isRandom 来自上一个页面
	if (event.articleType) {
		this.articleType = event.articleType
	}
  },
  onUnload() {
    
  },
  onPageScroll(e) {
    // 计算封面高度
    const coverHeight = this.coverImage.height - 100 > 0 ? this.coverImage.height - 100 : 200
    // 根据滚动位置判断是否显示导航栏
    if (e.scrollTop > coverHeight) {
      this.showNavBar = true
    } else {
      this.showNavBar = false
    }
  },
  methods: {
	  //关注按钮点击
	  onClick() {
	  	this.followChecked = !this.followChecked
		let way = this.followChecked ? 'add' : 'del'
	  	//发送请求，
		request({
			url: '/collectUser/' + way,
			method: 'post',
			data: {
				fromArticleId: this.article.id,  //文章id
				toUserId: this.article.authorId,//作者id
				articleType: this.article.ai? 0 : 1,//文章类型
				userId: getUserInfo().userId//用户id
			}
		}).then(res => {
			console.log(res)
		})
	  },
	//时间倒计时
	countdown() {
		//15s倒计时
		let timer = setInterval(() => {
			if(this.time<=0) clearInterval(timer)
			this.time -= 1000
		},1000)
	},
	//获取加载数据
	getLoadData() {
		//根据是否随机获取数据，还是指定获取数据，发送不同请求
		let url = this.isRandom ? 'getRandomById' : 'getById'
		request({
			url: `/articles/${url}`,
			method: 'get',
			data: {
				id: this.id,
				// articleType: this.articleType
			}
		}).then(res => {
			this.article = res.data
			console.log(res)
			//数据获取成功，关闭加载,倒计时开始
			this.followChecked = res.data.followAuthor || false
			this.likeChecked = res.data.likeArticle || false
			this.collectChecked = res.data.collectArticle || false
			this.loading = false
			this.countdown()
		})
	},
    // 将时间戳转换为可读的时间格式
    publishTime(timestamp) {
      return translatePublishTime(timestamp)
    },
    // 返回上一页或者跳转到文章列表页
    back() {
      // 获取当前页面数量
      const pages = getCurrentPages().length
      // 定义文章列表页的路径
      const pageUrl = '/pages/photo/list/list.nvue'

      // 如果当前页面数量大于1，返回上一页
      if (pages > 1) {
        uni.navigateBack({})
      } else { // 否则跳转到文章列表页
        uni.redirectTo({
          url: pageUrl,
          fail: (e) => {
            // 如果跳转失败，说明当前页面是tabbar页面，需要使用switchTab跳转
            if (e.errMsg.indexOf('tabbar') !== -1) {
              uni.switchTab({
                url: pageUrl
              })
			}
          }
        })
      }
    },
    //将文章加入阅读历史
    setReadHistory() {
      // 获取阅读历史缓存，如果不存在则为空数组
      const historyCache = uni.getStorageSync('readHistory') || []
      // 过滤掉当前文章的阅读历史
      const readHistory = historyCache.filter(item => item.article_id !== this.id)
      // 将当前文章的阅读历史添加到数组最前面
      readHistory.unshift({
        article_id: this.id,
        last_time: Date.now()
      })
      // 将更新后的阅读历史缓存到本地
      uni.setStorageSync('readHistory', readHistory)

    },
    // 加载数据
    loadData(id) {
		this.getLoadData()
        // 将文章添加进阅读历史
        this.setReadHistory()
    },
    // 设置封面图片的大小
    setCoverImageSize(e) {
      const {width, height} = e.detail // 获取图片的宽和高
      uni.getSystemInfo({ // 获取系统信息
        success: ({windowWidth}) => { // 获取系统信息成功
          this.coverImage.width = windowWidth // 将封面图片的宽度设置为窗口宽度
          this.coverImage.height = (windowWidth / width) * height // 封面高度；将封面图片的高度设置为宽高比乘以窗口宽度
          this.coverImage.show = true // 显示封面图片
        }
      })

    },
	//点击头像，进入他人信息页面
	goOtherInfoPage() {
		uni.navigateTo({
			url: '/pages/common/otherInformation/index?id=' + this.article.authorId
		})
	},
	//点击收藏文章按钮
	onCollectClick() {
		this.collectChecked = !this.collectChecked
		//发送请求，更改后端数据
		let way = this.collectChecked ? 'add' : 'del'
		request({
			url: '/collectArticle/' +  way,
			method: 'post',
			data: {	  
				userId: getUserInfo().userId,			
				toArticleId: this.id,			  
				articleType: this.article.ai ? 0 : 1//文章类型，1为普通文章，0为ai文章
			}
		}).then(res => {
			console.log(res)
		})
	},
	//点击点赞按钮
	addLikeCount() {
		  this.likeChecked = !this.likeChecked
		  //发送请求，更改后端数据
		  let way = this.likeChecked ? 'add' : 'del'
		  request({
			  url: '/likeArticle/' +  way,
			  method: 'post',
			  data: {	  
				  userId: getUserInfo().userId,			
				  toArticleId: this.id,			  
				  articleType: this.article.ai ? 0 : 1//文章类型，1为普通文章，0为ai文章
			  }
		  }).then(res => {
			  console.log(res)
		  })
		  
	},
	//点击关注用户按钮
	onClickFollowUser() {
		this.followChecked = !this.followChecked
		let way = this.followChecked ? 'add' : 'del'
		request({
			url: '/followUser/' + way,
			method: 'post',
			data: {
			  userId: getUserInfo().userId,
			  toUserId: this.article.authorId,
			  fromArticleId: this.id,
			  articleType: this.article.ai ? 0 : 1//文章类型，1为普通文章，0为ai文章
			}
		}).then(res => {
			console.log(res)
		})
	},
	//点击私信，跳转私信页面
	goPageChat() {
		uni.navigateTo({
			url: '../../privateChat/index?receiverid=' + this.article.authorId +'&chatObject=' + this.article.authorName
		})
	},
	//显示还有多少时间到时
	showTimecCountdown() {
		uni.showModal({
			showCancel: false,
			content: `请${this.time/1000}秒后再试`,
			success: function (res) {
				if (res.confirm) {
					console.log('用户点击确定');
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		})
	},
	
  },

}
</script>

<style scoped lang="scss">

page{
	background-color: #fff !important;
}

/* #ifdef APP-NVUE */
.article {
  background-color: #fff;
}

/* #endif */

@mixin cp {
  padding: 0 40rpx;
}

.article {
  background-color: #fff;
  min-height: 100vh;
}

.favBtn_author {
	margin-left: 30rpx;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;

  .back {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, .75);
    display: flex;
    justify-content: center;
    align-items: center;

    .icon {
      transform: translate(-2rpx, 2rpx);
      /* #ifdef APP-NVUE */
      transform: translate(-2rpx, 0);
      /* #endif */
    }
  }

  .title {
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    text-align: center;
    /* #ifndef APP-NVUE */
    height: 100%;
    width: 100%;
    /* #endif */
    /* #ifdef APP-NVUE */
    height: 44px;

    /* #endif */
    .text {
      font-size: 32rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      /* #ifndef APP-NVUE */
      display: block;
      width: 100%;
      /* #endif */
      /* #ifdef APP-NVUE */
      lines: 1
      /* #endif */
    }
  }

  &.show {
    background-color: #fff;

    .back {
      background-color: transparent;
    }

    .title {
      opacity: 1;

      .text {
        color: #333;
      }
    }
  }
}

.detail-loading {
  margin: 100rpx auto 0;
  width: 35px;
  height: 35px;
  animation: rotate360 2s linear infinite;
}

@keyframes rotate360 {
  0% {
    transform: rotate(0deg);
    transform-origin: center center;
  }

  100% {
    transform: rotate(360deg);
    transform-origin: center center;
  }
}

.cover {
  position: relative;
  z-index: 0;
  background: #fff;
  transition: height .1s;
  height: 270rpx;
  overflow: hidden;

  &.placeholder {
    //height: 600rpx;
  }

  &.not-cover {
    background: transparent;
    //height: 200rpx;

    .img {
      display: none;
    }
  }

  .img {
    opacity: 1;
    transition: opacity .3s;
	background-size: cover;

    &.show {
      opacity: 1;
    }
  }

  .mask {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1;
    background-image: linear-gradient(to bottom, transparent, #fff);
  }
}

.meta {
  @include cp;
  margin-top: -40rpx;
  position: relative;
  z-index: 1;

  .title {
    .text {
      font-size: 44rpx;
      line-height: 66rpx;
      font-weight: bold;
    }
  }

  .excerpt {
    margin-top: 10rpx;

    .text {
      font-size: 26rpx;
      line-height: 40rpx;
      color: #666;
    }
  }

  .author {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-direction: row;
    margin-top: 20rpx;

    .at,
    .split,
    .date {
      font-size: 26rpx;
      color: #999;
    }

    .split {
      margin: 0 10rpx;
    }
	
	img {
		display: block;
		width: 70rpx;
		height: 70rpx;
		margin: 0 20rpx 0 0;
		border-radius: 50%;
	}
  }
}

.content {
  @include cp;
  margin-top: 40rpx;
  padding-bottom: 70rpx;
}

.formData {
	    position: fixed;
	    bottom: 0;
	    width: 100%;
	    padding: 0 40rpx;
	    height: 90rpx;
	    background-color: #fff;
	    display: flex;
	    flex-direction: row-reverse;
	    border: 1px solid #f1f1f1;
	    align-items: center;
	
	view {
		display: flex;
		align-items: center;
		margin-left: 20rpx;
		height: 25rpx;
	}
	
	.favBtn {
		margin-left: 20rpx;
	}
}
</style>
